<?php
class ListView extends CWidget
{
	/**
	 * @var IDataProvider the data provider for views;
	 */
	public $dataProvider;
	/**
	 * @var string the view used for rendering each data item
	 */
	public $itemView;
	/**
	 * @var string the template to be used to control the layout of various sections in the view;
	 */
	public $template = "{items}\n{pager}";
	/**
	 * @var array the configuration for items html options.
	 */
	public $itemsHtmlOptions = array('class' => 'items');
	/**
	 * @var array the configutation for pager html options.
	 */
	public $pagerHtmlOptions = array('class' => 'pager');
	
	public function init()
	{
		if (null === $this->dataProvider)
			throw new Exception('The "dateProvider" property can not be empty');
	}
	
	public function run()
	{
		$this->renderContent();
	}
	
	/**
	 * render all
	 */
	public function renderContent()
	{
//		ob_start();
		preg_replace_callback('/{(\w+)}/', array($this, 'renderSection'), $this->template);
//		ob_end_clean();
	}
	
	/**
	 * render a section
	 * @param array
	 */
	public function renderSection($matches)
	{
		$method = 'render' . $matches[1];
		if (method_exists($this, $method)) {
			$this->$method();
		}
	}
	
	/**
	 * render items
	 */
	public function renderItems()
	{
	    $owner = $this->getOwner();
	    echo CHtml::openTag('div', $this->itemsHtmlOptions);
		foreach ($this->dataProvider->getData() as $index=>$data) {
		    $owner->renderPartial($this->itemView, array(
		        'data' => $data,
		        'index' => $index,
		    ));
		}
		echo CHtml::closeTag('div');
	}
	
	/**
	 * render pager
	 */
	public function renderPager()
	{
	    echo CHtml::openTag('div', $this->pagerHtmlOptions);
	    $this->widget('LinkPager', array(
	        'pages' => $this->dataProvider->getPagination(),
	    ));
	    echo CHtml::closeTag('div');
	}
}